package com.jy.api.dao;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lihu on 2017/12/12.
 */
public class OrderItemDaoImpl {

    @Autowired
    JdbcTemplate jdbcTemplate;

    public List<Map<String, Object>> getProductTotal(String storeId, List<String> typeIds,
                                                     String productId, Date start, Date end) {
        Map map = new HashMap();
        String sql = "select b.product_id productId,b.product_name productName,sum(b.quantity) quantity,sum(b.sales_price) amount" +
                " FROM `order` a LEFT JOIN " +
                " order_item b on(a.id=b.order_id) WHERE " +
                " a.store_id=:storeId AND a.status='FINISHED' AND a.type='SALES' and" +
                " b.enabled=1 and payment_time BETWEEN :fromTime AND :endTime AND b.product_id IS NOT NULL";
        if (StringUtils.isNotBlank(productId)) {
            sql += " AND b.product_id =:productId";
            map.put("productId", productId);
        } else if (typeIds.size() > 0) {
            sql += " AND  b.product_type_id IN (:typeIds)";
            map.put("typeIds", typeIds);
        }
        sql += " GROUP BY productId,productName order BY quantity DESC";
        map.put("storeId", storeId);
        map.put("fromTime", start);
        map.put("endTime", end);
        NamedParameterJdbcTemplate namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(jdbcTemplate);
        return namedParameterJdbcTemplate.queryForList(sql, map);

    }

    public List<Map<String, Object>> getMemberTotal(String storeId, Date start, Date end) {
        String sql = "select sum(amount) amount,count(*) quantity " +
                " FROM `order` WHERE store_id=? AND status='FINISHED' AND type='MEMBER_DEPOSIT'  ";
        return jdbcTemplate.queryForList(sql, storeId, start, end);
    }


}
